//
//  SetnewpwdViewController.m
//  LocomotiveGuards
//
//  Created by admin on 15/11/19.
//  Copyright (c) 2015年 REDOOR. All rights reserved.
//

#import "SetnewpwdViewController.h"
#import "PopLoadMsg.h"
#import "PopMsg.h"
#define kAlphaNum @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

@interface SetnewpwdViewController ()
{
    UITextField *_setnewpwd;
    UITextField *_confirmpwd;
    UIButton *_btnLast;
    UILabel *_tipLabel;
    UIButton *_btnCompete;
    UILabel *_newtipLabel;
    BOOL start;
    BOOL end;
    NSMutableString *result;
    NSInteger flagPhone;
    UILabel *label_confirmpwd;
    UILabel *label_pwd;
}

@end

@implementation SetnewpwdViewController
@synthesize phone,verificationCode;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.leftbtn setTitle:@"" forState:UIControlStateNormal];
    [self.leftbtn setImage:[UIImage imageNamed:@"back01"] forState:UIControlStateNormal];
    [self addTitle:@"忘记密码"];
    [self configview];
}

-(void)configview{
    label_pwd = [[UILabel alloc] initWithFrame:CGRectMake(20*W, 140*H, SCREEN_WIDTH-40*W, 30*H)];
    label_pwd.text = @"设置新密码";
    label_pwd.textAlignment = 1;
    label_pwd.textColor = [UIColor whiteColor];
    label_pwd.font = [UIFont systemFontOfSize:26];
    
    [self.view addSubview:label_pwd];
    
    _setnewpwd = [[UITextField alloc] initWithFrame:CGRectMake(20*W, CGRectGetMaxY(label_pwd.frame)+20*H, SCREEN_WIDTH-40*W, 35*H)];
    _setnewpwd.backgroundColor = [UIColor whiteColor];
    _setnewpwd.borderStyle = UITextBorderStyleRoundedRect;
    _setnewpwd.keyboardType=UIKeyboardTypeASCIICapable;
    _setnewpwd.placeholder = @"6-12位字母或数字";
    _setnewpwd.textAlignment = 1;
    _setnewpwd.secureTextEntry=YES;
    _setnewpwd.font = [UIFont systemFontOfSize:17];
    NSString *pwd=[[NSUserDefaults standardUserDefaults]objectForKey:@"yiwan_pwd"];
    if(pwd){
        _setnewpwd.text=pwd;
    }
    _setnewpwd.delegate = self;
    [self.view addSubview:_setnewpwd];
    
    _tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(20*W, CGRectGetMaxY(_setnewpwd.frame)+15*H, SCREEN_WIDTH-40*W, 15*H)];
    _tipLabel.text = @"※验证码错误请重新输入";
    _tipLabel.textColor = [UIColor cyanColor];
    _tipLabel.textAlignment = 1;
    _tipLabel.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:_tipLabel];
    _tipLabel.hidden = YES;
    
    label_confirmpwd = [[UILabel alloc] initWithFrame:CGRectMake(20*W, CGRectGetMaxY(_tipLabel.frame)+20, SCREEN_WIDTH-40*W, 30*H)];
    label_confirmpwd.text = @"确认新密码";
    label_confirmpwd.textAlignment = 1;
    label_confirmpwd.textColor = [UIColor whiteColor];
    label_confirmpwd.font = [UIFont systemFontOfSize:26];
    
    [self.view addSubview:label_confirmpwd];
    
    _confirmpwd = [[UITextField alloc] initWithFrame:CGRectMake(20*W, CGRectGetMaxY(label_confirmpwd.frame)+20*H, SCREEN_WIDTH-40*W, 35*H)];
    _confirmpwd.backgroundColor = [UIColor whiteColor];
    _confirmpwd.keyboardType=UIKeyboardTypeASCIICapable;
    _confirmpwd.borderStyle = UITextBorderStyleRoundedRect;
    _confirmpwd.placeholder = @"确认密码";
    _confirmpwd.textAlignment = 1;
    _confirmpwd.secureTextEntry=YES;
    _confirmpwd.font = [UIFont systemFontOfSize:17];
    _confirmpwd.delegate = self;
    NSString *confirmpwd=[[NSUserDefaults standardUserDefaults]objectForKey:@"yiwan_confirmpwd"];
    if(confirmpwd){
        _confirmpwd.text=confirmpwd;
    }

    [self.view addSubview:_confirmpwd];
    
    _newtipLabel = [[UILabel alloc] initWithFrame:CGRectMake(20*W, CGRectGetMaxY(_confirmpwd.frame)+15*H, SCREEN_WIDTH-40*W, 15*H)];
    _newtipLabel.text = @"※验证码错误请重新输入";
    _newtipLabel.textColor = [UIColor cyanColor];
    _newtipLabel.textAlignment = 1;
    _newtipLabel.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:_newtipLabel];
    _newtipLabel.hidden = YES;
    
    _btnCompete = [UIButton buttonWithType:UIButtonTypeCustom];
    _btnCompete.frame = CGRectMake(SCREEN_WIDTH-100*W, SCREEN_HEIGHT-90*H, 60*W, 30*H);
    [_btnCompete setTitle:@"完成" forState:UIControlStateNormal];
    
    _btnCompete.titleLabel.font = [UIFont systemFontOfSize:20];
    [_btnCompete addTarget:self action:@selector(btnComepeteClicked) forControlEvents:UIControlEventTouchUpInside];
    if(_setnewpwd.text.length==0 ||_confirmpwd.text.length==0){
        [self disableButton:_btnCompete];
    }
    else{
        [self enableButton:_btnCompete];
    }
    
    [self.view addSubview:_btnCompete];
    
    _btnLast = [UIButton buttonWithType:UIButtonTypeCustom];
    _btnLast.frame = CGRectMake(40*W, SCREEN_HEIGHT-90*H, 60*W, 30*H);
    [_btnLast setTitle:@"上一步" forState:UIControlStateNormal];
     _btnLast.titleLabel.font = [UIFont systemFontOfSize:20];
    [_btnLast addTarget:self action:@selector(btnLastClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnLast];

}

-(void)btnLastClicked{
    [[NSUserDefaults standardUserDefaults]setObject:_setnewpwd.text forKey:@"yiwan_pwd"];
    [[NSUserDefaults standardUserDefaults]setObject:_confirmpwd.text forKey:@"yiwan_confirmpwd"];
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)btnComepeteClicked{
    int i=[self checkIsHaveNumAndLetter:_setnewpwd.text];
    if(_setnewpwd.text.length<6){
        _tipLabel.frame=CGRectMake(20*W, CGRectGetMaxY(_setnewpwd.frame)+15*H, SCREEN_WIDTH-40*W, 15*H);
        _tipLabel.numberOfLines=1;
        _tipLabel.text=@"※密码低于6位,请重新输入";
        _tipLabel.hidden=NO;
    }
    else if(i==0){
        _tipLabel.frame=CGRectMake(20*W, CGRectGetMaxY(_setnewpwd.frame), SCREEN_WIDTH-40*W, 50*H);
        _tipLabel.numberOfLines=0;
        _tipLabel.text=@"※密码必须包括大小写字母和数字，请重新输入";
        _tipLabel.hidden=NO;
    }
    else if(![_setnewpwd.text isEqualToString:_confirmpwd.text]){
        _newtipLabel.text=@"※两次密码输入不一致,请重新输入";
        _newtipLabel.hidden=NO;
    }
    
    else{
        [self dorequest];
        _tipLabel.hidden=YES;
        _newtipLabel.hidden=YES;
    }
}

-(void)dorequest{
    start=YES;
    end=YES;
    PopLoadMsg *loadmsg=[PopLoadMsg new];
    
    NSDictionary *paramdic=@{@"loginId":phone,
                             @"loginPwd":_confirmpwd.text,
                             @"verificationCode":verificationCode
                             };
    NSString *url = [urlstring stringByAppendingString:@"setPwd.do"];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        sleep(startloadtime);
        dispatch_async(dispatch_get_main_queue(), ^{
            if(start==YES){
                [loadmsg loadImages];
            }
        });
    });
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        sleep(startloadtime+endloadtime);
        dispatch_async(dispatch_get_main_queue(), ^{
            end=NO;
            if(start==NO){
                [loadmsg.imageview removeFromSuperview];
            }
        });
    });
    
    [K_AppDelegate GenerateHTTPRequestWithUrl:url withParam:paramdic success:^(AFHTTPRequestOperation *op,id responseObject){
        start=NO;
        if(end==NO){
            [loadmsg.imageview removeFromSuperview];
        }
        NSDictionary *dic = [NSDictionary new];
        if ([responseObject isKindOfClass:[NSData class]]) {
            NSLog(@"responseObject = %@", responseObject);
            dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        }
        else if ([responseObject isKindOfClass:[NSDictionary class]])
        {
            dic = responseObject;
        }
        
        flagPhone = [[dic objectForKey:@"flag"] integerValue];
        NSString *msg = [dic objectForKey:@"msg"];
        if (msg) {
            NSString *message=[msg stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            if(flagPhone==0){
                [PopMsg showMessage:@"修改密码成功" Lasttime:1.0f];
            }
            else{
                [PopMsg showMessage:message Lasttime:1.0f];
            }
        }
        
        [self donext];
        NSLog(@"flagPhone = %i", flagPhone);
        
    }failure:^(AFHTTPRequestOperation *op,NSError *error){
        start=NO;
        if(end==NO){
            [loadmsg.imageview removeFromSuperview];
        }
        NSLog(@"error = %@", error);
        [PopMsg showMessage:@"网络出错" Lasttime:1.0f];
    }];

}

-(void)donext{
    if(flagPhone==0){
        
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"操作已成功!" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }

}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"yiwan_confirmpwd"];
    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"yiwan_pwd"];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    if(_setnewpwd.text.length!=0 && _confirmpwd.text.length!=0 && _setnewpwd!=nil&&_confirmpwd!=nil){
        [self enableButton:_btnCompete];
    }
    else{
        [self disableButton:_btnCompete];
    }
    if(textField==_confirmpwd){
        label_pwd.frame=CGRectMake(CGRectGetMinX(label_pwd.frame), CGRectGetMinY(label_pwd.frame)+80*H, CGRectGetWidth(label_pwd.frame), CGRectGetHeight(label_pwd.frame));
        _setnewpwd.frame=CGRectMake(CGRectGetMinX(_setnewpwd.frame), CGRectGetMinY(_setnewpwd.frame)+80*H, CGRectGetWidth(_setnewpwd.frame), CGRectGetHeight(_setnewpwd.frame));
        _tipLabel.frame=CGRectMake(CGRectGetMinX(_tipLabel.frame), CGRectGetMinY(_tipLabel.frame)+80*H, CGRectGetWidth(_tipLabel.frame), CGRectGetHeight(_tipLabel.frame));
        _newtipLabel.frame=CGRectMake(CGRectGetMinX(_newtipLabel.frame), CGRectGetMinY(_newtipLabel.frame)+80*H, CGRectGetWidth(_newtipLabel.frame), CGRectGetHeight(_newtipLabel.frame));
        _confirmpwd.frame=CGRectMake(CGRectGetMinX(_confirmpwd.frame), CGRectGetMinY(_confirmpwd.frame)+90*H, CGRectGetWidth(_confirmpwd.frame), CGRectGetHeight(_confirmpwd.frame));
        label_confirmpwd.frame=CGRectMake(CGRectGetMinX(label_confirmpwd.frame), CGRectGetMinY(label_confirmpwd.frame)+80*H, CGRectGetWidth(label_confirmpwd.frame), CGRectGetHeight(label_confirmpwd.frame));
    }

}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    if(textField==_confirmpwd){
        label_pwd.frame=CGRectMake(CGRectGetMinX(label_pwd.frame), CGRectGetMinY(label_pwd.frame)-80*H, CGRectGetWidth(label_pwd.frame), CGRectGetHeight(label_pwd.frame));
        _setnewpwd.frame=CGRectMake(CGRectGetMinX(_setnewpwd.frame), CGRectGetMinY(_setnewpwd.frame)-80*H, CGRectGetWidth(_setnewpwd.frame), CGRectGetHeight(_setnewpwd.frame));
        _tipLabel.frame=CGRectMake(CGRectGetMinX(_tipLabel.frame), CGRectGetMinY(_tipLabel.frame)-80*H, CGRectGetWidth(_tipLabel.frame), CGRectGetHeight(_tipLabel.frame));
        _newtipLabel.frame=CGRectMake(CGRectGetMinX(_newtipLabel.frame), CGRectGetMinY(_newtipLabel.frame)-80*H, CGRectGetWidth(_newtipLabel.frame), CGRectGetHeight(_newtipLabel.frame));
        _confirmpwd.frame=CGRectMake(CGRectGetMinX(_confirmpwd.frame), CGRectGetMinY(_confirmpwd.frame)-90*H, CGRectGetWidth(_confirmpwd.frame), CGRectGetHeight(_confirmpwd.frame));
        label_confirmpwd.frame=CGRectMake(CGRectGetMinX(label_confirmpwd.frame), CGRectGetMinY(label_confirmpwd.frame)-80*H, CGRectGetWidth(label_confirmpwd.frame), CGRectGetHeight(label_confirmpwd.frame));
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//    textField.secureTextEntry=NO;
    if(textField.text.length>11){
        if ([string isEqual:@""])
        {
            return YES;
        }
        return NO;
    }
    
    NSCharacterSet *cs;
    cs = [[NSCharacterSet characterSetWithCharactersInString:kAlphaNum] invertedSet];
    
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; //按cs分离出数组,数组按@""分离出字符串
    
    BOOL canChange = [string isEqualToString:filtered];
    
    return canChange;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [_setnewpwd resignFirstResponder];
    [_confirmpwd resignFirstResponder];
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [_setnewpwd resignFirstResponder];
    [_confirmpwd resignFirstResponder];
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(int)checkIsHaveNumAndLetter:(NSString*)pPassword{
    //數字條件
    NSRegularExpression *tNumRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[0-9]" options:NSRegularExpressionCaseInsensitive error:nil];
    
    //符合數字條件的有幾個字元
    int tNumMatchCount = [tNumRegularExpression numberOfMatchesInString:pPassword
                                                                options:NSMatchingReportProgress
                                                                  range:NSMakeRange(0, pPassword.length)];
    
    //大写字母條件
    NSRegularExpression *tLetterRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[A-Z]" options:NSRegularExpressionAllowCommentsAndWhitespace error:nil];
    
    //符合大写字母條件的有幾個字元
    int tLetterMatchCount = [tLetterRegularExpression numberOfMatchesInString:pPassword options:NSMatchingReportProgress range:NSMakeRange(0, pPassword.length)];
    
    
    //小写字母條件
    NSRegularExpression *littleLetterRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[a-z]" options:NSRegularExpressionAllowCommentsAndWhitespace error:nil];
    
    //符合小写字母條件的有幾個字元
    int littleLetterMatchCount = [littleLetterRegularExpression numberOfMatchesInString:pPassword options:NSMatchingReportProgress range:NSMakeRange(0, pPassword.length)];
    
    
    if (tNumMatchCount == pPassword.length)
    {
        //全部符合數字，表示沒有英文
        return 0;
    }
    else if (tLetterMatchCount == pPassword.length)
    {
        //全部符合大写字母，表示沒有數字
        return 0;
    }
    else if(littleLetterMatchCount==pPassword.length){
        //全部符合小写字母，表示沒有數字
        return 0;
    }
    else if (tNumMatchCount + tLetterMatchCount == pPassword.length)
    {
        //数字和大写字母相加为密码长度，表示没有小写字母
        return 0;
    }
    else if (tNumMatchCount + littleLetterMatchCount == pPassword.length)
    {
        //数字和小写字母相加为密码长度，表示没有大写字母
        return 0;
    }
    else if (littleLetterMatchCount + tLetterMatchCount == pPassword.length)
    {
        //小写字母和大写字母相加为密码长度，表示没有数字
        return 0;
    }
    else
    {
        return 1;
        //可能包含標點符號的情況，或是包含非英文的文字，這裡再依照需求詳細判斷想呈現的錯誤
    }
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
